<template>
  <div>
    <BreakSpace label="采购订单信息" :containerStyle="{ marginBottom: '15px' }" />
    <FormPanel :list="topFilterList" :cols="3" :labelWidth="100" :collapse="false" :isSubmitBtn="false" />

    <BreakSpace label="备件列表" :containerStyle="{ marginBottom: '15px' }" />
    <!-- <span>
      订购品种合计： <el-input style="width:150px;" label="订购品种合计" size="medium" :disabled="true" v-model="dataSize"></el-input>
    </span> -->
    <FilterTable
      ref="mainTable"
      :columns="tableColumns"
      columnsRef="aduitOrder"
      :datakey="'records'"
      selectionType="single"
      :dataSource="dataSource"
      :isSelectColumn= false
      :onColumnsChange="columns => (this.tableColumns = columns)"
      height="auto"
    >
    </FilterTable>
    <div :style="{ position: 'fixed', left: 0, bottom: 0, right: 0, zIndex: 9,  borderTop: '1px solid #e9e9e9',
      padding: '10px 20px', background: '#fff', textAlign: 'right', }" >
      <multiuse-button type="primary"  @click="queryStockHandle" :loading="isQueryStock">
        查询库存</multiuse-button>
      <multiuse-button type="primary" @click="aduit(10041001)">审核通过</multiuse-button>
      <multiuse-button type="primary" @click="aduit(10041002)">审核驳回</multiuse-button>
      <multiuse-button type="primary" @click="closeDialogTop">关 闭</multiuse-button>
    </div>
    <Drawer :visible.sync="visible" :title="'预授权详细'" destroyOnClose width="100%" :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <editForm @close="editclose"  :rowData="rowData"></editForm>
    </Drawer>
  </div>
</template>
<script>
import { partbuyStockInItemOEM,auditOrder,queryStock } from '@/api/partsmanage/aduitOrder/index';
import { dictionary } from '@/utils/dictMixin';
import { getStorageList, querySysParam } from '@/api/part/common';
import editForm from '@/pages/claimDemage/BasicData/AuthQueryFactory/editForm';
import { getListByPage } from '@/api/claim/factory/AuthQueryFactory';


export default {
  components: {
    editForm
  },
  name: 'partBuyItems',
  props: {
    top: {}
  },
  mixins: [dictionary],
  data() {
    return {
      topFilterList: this.createTopFilterList(),
      tableColumns: this.createTableColumns(),
      fetchParams: {},
      dataSource: [],
      storageDic: [
        { text: 'OEM电', value: 'OEM-ELECTIC' },
        { text: 'OEM油', value: 'OEM-OIL' }
      ], // 仓库字典
      visible: false,
      loading: false,
      aduitRem:'',
      rowData:{},
      dataSize:0,
      isQueryStock: false, // 查询库存loading

    };
  },
  mounted() {
    // this.translate(this.top.CUSTOMER_CODE);
    // this.getStorage();
    if(this.top.XSDDLX != 30031003){
      this.topFilterList.find(x => x.fieldName == 'YSQDH').hidden = true;
    }
    this.findBuyItems();
  },
  methods: {
    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '服务商代码',
          fieldName: 'DEALER_CODE',
          initialValue: '',

          disabled: true
        },
        {
          type: 'INPUT',
          label: '服务商名称',
          fieldName: 'DEALER_NAME',
          initialValue: '',

          disabled: true
        },
        {
          type: 'INPUT',
          label: '备件订单号',
          fieldName: 'XSDDHM',
          initialValue: '',

          disabled: true
        },
        {
          type: 'SELECT',
          label: '订单类型',
          initialValue: '',

          fieldName: 'XSDDLX',
          itemList: this.createDictList('3003'),

          disabled: true
        },
        // {
        //   title: '订单金额',
        //   sorter: true,
        //   dataIndex: 'XSYSJE',
        //   precision: 2,
        //   filter: true,
        //   filterType: 'number'
        // },
        {
          type: 'INPUT',
          label: '订单金额',
          fieldName: 'XSYSJE',
          precision: 2,
          disabled: true,
          numberFormat: true
        },
        {
          type: 'DATE',
          fieldName: 'DDTBSJ',
          initialValue: '',

          label: '提报日期',
          dateFormat: 'yyyy-MM-dd',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '联系人',
          initialValue: '',

          fieldName: 'CONTACT_MAN',
          placeholder: '请输入...',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '联系电话',
          initialValue: '',

          fieldName: 'CONTACT_PHONE',
          placeholder: '请输入...',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '收货详细地址',
          initialValue: '',

          fieldName: 'XXSHDZ',
          placeholder: '请输入...',
          disabled: true
        },
        {
          type: 'SELECT',
          label: '发运方式',
          initialValue: '',
          fieldName: 'DDFYFS',
          itemList: this.createDictList('3024'),
          clearable:false
        },
        {
          type: 'SELECT',
          label: '是否免运费',
          initialValue: '',
          fieldName: 'DDMYF',
          itemList: this.createDictList('1004'),
          clearable:false
        },
        {
          type: 'INPUT',
          label: '预授权单号',
          initialValue: '',
          fieldName: 'YSQDH',
          // disabled: true,
          placeholder:'暂无',
          readonly: true,
          clearable: false,
          unitRender: () => {
            return (
              <div>
                <el-button icon="el-icon-search" onClick={() => this.seacherFun()}></el-button>
              </div>
            );
          }
        },
        {
          type: 'TEXT_AREA',
          label: '备注',
          initialValue: '',
          selfCols: 2,
          maxlength: 150,
          fieldName: 'XSDDBZ',
          placeholder: '请输入...',
          disabled: true
        },
        {
          type: 'TEXT_AREA',
          label: '审核说明',
          initialValue: '',
          selfCols: 2,
          maxlength: 150,
          fieldName: 'DDBHBZ',
          placeholder: '请输入...'
        }

      ];
    },
    editclose(){
      this.visible = false;
    },
    seacherFun(){
      let no = this.topFilterList.find(x => x.fieldName == 'YSQDH').initialValue
      if(no === undefined || no == null || no == ""){
        this.$notify.error('当前预授权单号为空!');
        return;
      }
      getListByPage({
        authNo:no,
        pageNum: 1,
        pageSize: 20,
        current: 1,
        currentPage: 1,
        limit: 20,
        size: 20}).then(res =>{
        if(res.data.records[0] === undefined || res.data.records[0] === null || res.data.records[0] === ""){
          this.$notify.error('当前预授权单号对应的预授权信息为空!');
          return;
        }
        if(res.data.records[0].authId === undefined || res.data.records[0].authId === null || res.data.records[0].authId === ""){
          this.$notify.error('当前预授权单号对应的预授权信息为空!');
          return;
        }
        this.rowData = {
          authId : res.data.records[0].authId
        }
        this.visible = true

      }).catch(res =>{
        this.$notify.error(res.errMsg);

      })
    },
    createTableColumns(flag) {
      const column = [
        {
          title: '序号',
          // sorter: true,
          width: 70,
          fixed: 'left',
          dataIndex: 'xuhao',
          sorter: true,
          render: props => {
            return <span>{props.row.$index + 1}</span>;
          }
        },
        {
          title: '备件代码',
          width: 150,
          sorter: true,
          fixed: 'left',
          dataIndex: 'BJXMBH',
          showOverflowTooltip: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '备件名称',
          width: 180,
          sorter: true,
          fixed: 'left',
          dataIndex: 'BJZWMC',
          showOverflowTooltip: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '物料组',
          sorter: true,
          dataIndex: 'MATERIAL',
          showOverflowTooltip: true,
          filter: true,
          filterType: 'input',
          filterItems: this.createDictList(3054),
          dictItems: this.createDictList(3054)
        },
        // {
        //   title: '单位',
        //   width: 180,
        //   sorter: true,
        //   dataIndex: 'BJDANW',
        //   showOverflowTooltip: true,
        //   filter: true,
        //   filterType: 'input'
        // },
        {
          title: '销售包装量',
          sorter: true,
          dataIndex: 'IN_SERVICE_AMOUNT',
          filter: true,
          filterType: 'number',
          min: 0,
          max: Infinity,
        },
        {
          title: '服务商进价',
          sorter: true,
          dataIndex: 'JJHDJ',
          precision: 2,
          filter: true,
          filterType: 'number',
          numberFormat: true
        },
      ];

      const stock = this.createDictList(3040);
      console.log("isStock",stock)
      const column2 = [
        {
          title: '可用库存',
          sorter: true,
          dataIndex: 'availableQuantity',
        }
      ];

      const column3 = [
        {
          title: '订购数量',
          sorter: true,
          dataIndex: 'BSTXSL',
          filter: true,
          filterType: 'number',
          min: 0,
          max: Infinity,
          summation: true,
          summationUnit:"(订购数量合计)",
        },
        {
          title: '订购金额(元)',
          sorter: true,
          dataIndex: 'XSYSJE',
          precision: 2,
          summation: true,
          summationUnit:"(订购金额合计)",
          filter: true,
          filterType: 'number',
          numberFormat: true
        },
      ];


      if (flag) {
        return column.concat(column3,column2);
      } else {
        return column.concat(column3,column2);
      }
    },
    //  changeSelect() {
    //         this.form.tableData = [];

    //     },

    // refuByPurchase() {
    //   this.aduitRem = null;
    //   this.visible = true


    // },
    closeDialogTop(){
      this.$emit('cancel');
    },
    aduit(e) {
      let params = {
        id: this.top.ID,
        type:e,
        shipType:this.topFilterList.find(x => x.fieldName == 'DDFYFS').initialValue,
        isDdmyf:this.topFilterList.find(x => x.fieldName == 'DDMYF').initialValue,
        aduitRem:this.topFilterList.find(x => x.fieldName == 'DDBHBZ').initialValue
      }

      if(e === 10041001){//通过

      }else if(e === 10041002){//驳回
        if(params.aduitRem === undefined || params.aduitRem === null || params.aduitRem === ""){
          this.$notify.error('驳回时审核说明不能为空!');
          return;
        }

      }else{
        this.$notify.error('传参错误!');
        return;
      }
      auditOrder(params).then(res => {
        if(res.success){
          this.$notify.success('审核成功!');
          // 请求执行成后，刷新主页面子表格
          this.$emit('cancel');
        }else{
          this.$notify.error(res.errMsg);

        }
      }).catch(err =>{
        this.$notify.error(err || "审核失败！");
      })

    },

    // 查询库存
    queryStockHandle() {
      this.tableColumns = this.createTableColumns(true)
      this.isQueryStock = true;
      queryStock(this.dataSource.map(item => item.BJXMBH)).then(res => {
        this.isQueryStock = false;
        const _data = _.cloneDeep(this.dataSource);
        _data.forEach((item,index) => {
          let isHasStock = res.data[index].available;
          let availableQuantity1 = res.data[index].availableQuantity;
          console.log ('库存查询按钮触发时的availableQuantity',availableQuantity1);
          item.isHasStock = isHasStock || '';
          item.availableQuantity = availableQuantity1;
        })
        this.dataSource = _data
      });
    },

    // async translate(dealerCode) {
    //   let name = '';
    //   let res = await byAllInfo({ dealerCode: dealerCode });
    //   if (res.resultCode == 200 && res.data && res.data.records && res.data.records.length > 0) {
    //     name = res.data.records[0].companyName;
    //   }
    //   this.topFilterList.find(x => x.fieldName == 'ownerName').initialValue = name;
    // },
    async getStorage() {
      const ckRes = await getStorageList();
      const ckDict = ckRes.data.map(x => ({ text: x['STORAGE_NAME'], value: x['STORAGE_CODE'] }));
      this.storageDic = ckDict;
      this.tableColumns.find(x => x.dataIndex == 'STORAGE_CODE').filterItems = this.tableColumns.find(x => x.dataIndex == 'STORAGE_CODE').dictItems = ckDict;
    },
    async findBuyItems() {
      this.topFilterList.map(x => {
        x.initialValue = this.top[x.fieldName];
      });
      let res = await partbuyStockInItemOEM({ partOrderId: this.top.ID });
      this.dataSize = res.data.length
      this.dataSource = res.data;
    }
  }
};
</script>
